class Register {
    constructor() {
        this.form = document.querySelector('.login-form');
        this.username = document.querySelector('#username');
        this.password = document.querySelector('#password');
        this.confirmPassword = document.querySelector('#confirm-password');
        this.nickname = document.querySelector('#nickname');
        
        this.init();
    }

    init() {
        this.form.addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleSubmit();
        });
    }

    // 表单验证
    validate() {
        // 用户名验证：4-12位字母数字下划线
        if (!this.username.value) {
            alert('请输入用户名');
            return false;
        }
        if (!/^[a-z0-9]\w{3,11}$/.test(this.username.value)) {
            alert('用户名必须是4-12位字母数字下划线');
            return false;
        }

        // 密码验证：6-12位字母数字下划线
        if (!this.password.value) {
            alert('请输入密码');
            return false;
        }
        if (!/\w{6,12}/.test(this.password.value)) {
            alert('密码必须是6-12位字母数字下划线');
            return false;
        }

        // 确认密码验证
        if (!this.confirmPassword.value) {
            alert('请确认密码');
            return false;
        }
        if (this.password.value !== this.confirmPassword.value) {
            alert('两次密码输入不一致');
            return false;
        }

        // 昵称验证
        if (!this.nickname.value) {
            alert('请输入昵称');
            return false;
        }

        return true;
    }

    // 处理表单提交
    async handleSubmit() {
        if (!this.validate()) return;

        try {
            const response = await fetch('http://localhost:8888/users/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    username: this.username.value,
                    password: this.password.value,
                    rpassword: this.confirmPassword.value,
                    nickname: this.nickname.value
                })
            });

            const data = await response.json();
            
            if (data.code === 1) {
                alert('注册成功！');
                window.location.href = 'login.html';
            } else {
                alert(data.message || '注册失败，请重试');
            }
        } catch (error) {
            alert('注册失败，请检查网络连接');
            console.error('注册错误：', error);
        }
    }
}

// 初始化注册功能
document.addEventListener('DOMContentLoaded', () => {
    new Register();
}); 